﻿App.MTruck = function() {
    return {

        currentFormValues: {},

        getStore: function() {
            var store = new Ext.data.Store({
            	autoLoad:true,
				baseParams:{start:0, limit:20},
				proxy: new Ext.data.HttpProxy({
					url : 'truck/items'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'truck_id',
					fields: [
					{
						name: 'truck_nbr',
						type: 'string'
					},
					{
						name: 'truck_type'
					},
					{
						name: 'truck_run_lic'
					},
					{
						name: 'truck_load',
						xtype : 'numberfield',
						allowBlank: false
					},
					{
						name: 'truck_fix_rec'
					},
					{
						name: 'names'
					},
					{
						name: "ownerList",
						convert: this.roleList
					}]
				})
            });
            return store;
        },


        getForm: function() {
            var form = new Ext.form.FormPanel({
				url:'truck/save',
                labelAlign: 'left',
                buttonAlign: 'center',
                bodyStyle: 'padding:5px',
                frame: true,
                labelWidth: 80,
                defaultType: 'textfield',
                defaults: {
                    allowBlank: true,
                    anchor: '90%',
                    enableKeyEvents: true
                },
                items: [{
                    xtype: 'hidden',
                    name: 'id',
                    value: ''
                },
                {
                    name: 'truck_nbr',
                    fieldLabel: '车牌号',
                    allowBlank:false
                },{
                    name: 'truck_type',
                    fieldLabel: '车型'
                },
                {
                    name: 'truck_run_lic',
                    fieldLabel: '行驶证'
                },
                {
                    name: 'truck_load',
                    fieldLabel: '载重'
                },
                {
                    name: 'truck_con',
                    fieldLabel: '车况'
                },
                {
                    name: 'truck_fix_rec',
                    fieldLabel: '维修记录'
                },
                {

                    xtype: 'panel',
                    //width: 330,
                   // height:350,
                    layout: 'fit',
//                    autoScroll:true,
                    bodyStyle: 'background:white',
                    items: [{
                        xtype: 'multiselect',
                        name: 'ownerList',
                        allowBlank: true,
//                        autoScroll:true,
                        width: 330,
                        height: 150,
                        enableKeyEvents: true,
                        valueField: "owner_id",
                        displayField: "name",
                        tbar: ["选择司机"],
                        store: new Ext.data.Store({
							autoLoad: true,
                            remoteSort: false,
							proxy: new Ext.data.HttpProxy({
								url : 'truckowner/ownerList'
							}),
                            reader: new Ext.data.JsonReader({
								totalProperty : 'totalCount',
								root : 'rows',
								idProperty : 'owner_id',
								fields: [{
									name: 'owner_id'
								},
								{
									name: 'name'
								}]
							})
                        }),
                        listeners: {
                            scope: this,
                            keypress: function(field, e) {
                                if (e.getKey() == 13) {
                                    this.submit();
                                }
                            }
                        }
                    }]
                
                }],
                buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
            });
            return form;
        },

        submit: function() {
            if (this.form.getForm().isValid()) {
                this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            if (action.result.method == "Create") {
                                this.form.getForm().reset();
                            } else {
                                this.dlg.hide();
                            }
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 400,
                height: 400,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.getForm().waitMsgTarget = fp.getEl();
                    }
                   
                }
            });
            return dlg;
        },
        highLight: function(value) {
            var key = App.MTruck.grid.store.baseParams.query;
            var v = value ? value.toString() : '';
            if (Ext.isString(v) & Ext.isString(key)) {
                if (key.length > 0) {
                    var re = new RegExp(key, "g");
                    return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
                } else {
                    return v;
                }
            } else {
                return v;
            }
        },
        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";

            var sm = new Ext.grid.CheckboxSelectionModel();

            this.grid = new Ext.grid.GridPanel({
            	tbar: new Ext.PagingToolbar({
            		pageSize: 20 ,//分页必须加的参数.最好和store里面的limit保持一致
                    displayInfo: true,
                    store: this.store,
                    items: ['-', 
                          {
                        text: '增加',
                        scope: this,
                        handler: this.add
                    },
//                    {
//                        text: '编辑',
//                        scope: this,
//                        handler: this.edit
//                    },
                    {
                        text: '删除',
                        scope: this,
                        handler: this.del
                    },
                    '-', new Ext.ux.form.SearchField({
                        store: this.store,
                        width: 110
                    })]
                }),
                plugins: [Ext.ux.plugins.Print],//打印按钮
                loadMask: true,
                viewConfig : {autoFill:false,forceFit:true},
                store: this.store,
                sm: sm,
                columns: [sm,new Ext.grid.RowNumberer(), {
                    header: "车牌号",
                    width: 80,
                    sortable: true,
                    dataIndex: 'truck_nbr',
                    renderer:this.highLight
                },
                {
                    header: "车型",
                    width: 100,
                    sortable: true,
                    dataIndex: 'truck_type',
                    renderer:this.highLight
                },
                {
                    header: "行驶证号",
                    width: 100,
                    sortable: true,
                    dataIndex: 'truck_run_lic',
                    renderer:this.highLight
                },
                {
                    header: "载重",
                    width: 100,
                    sortable: true,
                    dataIndex: 'truck_load',
                    renderer:this.highLight
                },
                {
                    header: "维修记录",
                    width: 100,
                    sortable: true,
                    dataIndex: 'truck_fix_rec',
                    renderer:this.highLight
                },
                {
                    header: "车主",
                    width: 100,
                    sortable: true,
                    dataIndex: 'name',
                    renderer:this.highLight
                }]
            });
            panel.add(this.grid);

        },
        
        add: function() {
            Ext.apply(this.currentFormValues, {
                id: '',
                name: "",
                password: "",
                confirmPassword: "",
                roleList: ""
            });
            this.dlg.setTitle("增加车辆信息");
            this.dlg.show();
        },

        edit: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                this.dlg.setTitle("编辑车辆信息");
                this.dlg.show();
            } else {
                Ext.Msg.alert('信息', '请选择要编辑的车辆。');
            }
        },

        del: function() {
            if (this.grid.getSelectionModel().hasSelection()) {
                var recs = this.grid.getSelectionModel().getSelections();
                var ids = [];
                for (var i = 0; i < recs.length; i++) {
                    ids.push(recs[i].json.truck_id);
                }
                Ext.Msg.confirm('删除车辆', '确定删除车辆？',
                function(btn) {
                    if (btn == 'yes') {
						Ext.Ajax.request({
							method:'post',
							url:'truck/remove',
							params:{
								ids:ids.toString()
							},
							success: function(resp, opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								if(result.success=='true') {
									Ext.Msg.alert('信息', info);
                                    App.MTruck.store.reload();
								}else {
                                    Ext.Msg.alert('信息', info);
                                }
							},
							failure: function(resp,opts) {
								var result = Ext.util.JSON.decode(resp.responseText);
								var info = result.info;
								Ext.Msg.alert('提示', info); 
							}
						});
                    }
                });
            } else {
                Ext.Msg.alert('信息', '请选择要删除的用户！');
            }
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getStore();
            };
            if (!this.form) {
                this.form = this.getForm();
            };
            if (!this.dlg) {
                this.dlg = this.getDialog();
            };
            this.createGrid(id);

        }
    };
} ();
